import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import beans.Person;

public class LoginServlet extends HttpServlet {


	private static final long serialVersionUID = -3054516715115982849L;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		getServletContext().getRequestDispatcher("/login.jsp").forward(req, resp);
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String resource = "/servlet/LoginServlet";		
		String email = req.getParameter("email");
		Person p = Dao.getPerson(email);
		
		if(p != null) {
			resource = "/servlet/" + capitalize(Person.TYPE_ID[p.type]) + "Servlet";
			req.getSession().setAttribute("person", p);
		}
		
		getServletContext().getRequestDispatcher(resource).forward(new HttpGetRequest(req), resp);
	}
	
	private String capitalize(String s) {
		return s.substring(0, 1).toUpperCase() +
				s.substring(1);
	}
	
	private class HttpGetRequest extends HttpServletRequestWrapper {

		public HttpGetRequest(HttpServletRequest request) {
			super(request);
		}
		
		public String getMethod() {
			return "GET";
		}
		
	}
	
}
